package com.ccepc.algmanage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ccepc.algmanage.service.ObsService;
import com.ccepc.algmanage.utils.AuthInfoUtils;
import com.ccepc.algmanage.utils.CommonUtils;
import com.ccepc.algmanage.utils.HkUtils;
import com.ccepc.common.core.util.R;
import com.ccepc.demo.api.dto.HkAuthsDto;
import com.ccepc.demo.api.entity.AlgConfigPoints;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.GetObjectRequest;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectRequest;
import com.obs.services.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;

@Slf4j
@Service
public class ObsServiceImpl implements ObsService {
    @Override
    public ResponseEntity<Object> uploadImage(MultipartFile file, ObsClient obsClient, String bucketName) {
        try {
            // 将文件上传到OBS
            PutObjectResult putObjectResult = obsClient.putObject(bucketName, file.getOriginalFilename(), file.getInputStream());
            // 关闭连接
            obsClient.close();
            return ResponseEntity.ok("File uploaded successfully. ETag: " + putObjectResult.getEtag());
        } catch (ObsException | IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @Override
    public ResponseEntity<Object> displayImage(String filename, ObsClient obsClient, String bucketName) {
        try {
            // 构造下载请求
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, filename);
            // 执行下载操作
            ObsObject obsObject = obsClient.getObject(getObjectRequest);
            // 获取文件输入流
            InputStream inputStream = obsObject.getObjectContent();
            // 从输入流中读取文件内容
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            byte[] fileData = outputStream.toByteArray();
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=" + filename);
            // 设置Content-Type响应头为image/*
            headers.add("Content-Type", "image/*");
            // 关闭连接
            obsClient.close();
            return new ResponseEntity<>(fileData, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @Override
    public ResponseEntity<Object> deleteImage(String filename, ObsClient obsClient, String bucketName) {
        try {
            // 删除文件
            obsClient.deleteObject(bucketName, filename);
            // 关闭连接
            obsClient.close();
            return ResponseEntity.ok(R.ok());
        } catch (ObsException | IOException e) {
            return ResponseEntity.status(
                    HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }

    @Override
    public byte[] uploadAndShowImg(
            ObsClient obsClient,
            String bucketName,
            String fileName,
            String picUrl
    ) {
        try {
            // 下载图片
            byte[] imageData = null;
            URL url = new URL(picUrl);
            try (InputStream inputStream = url.openStream()) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                IOUtils.copy(inputStream, outputStream);
                imageData = outputStream.toByteArray();
            }
            // 上传图片到华为云
            try {
                // 将文件上传到OBS
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, new ByteArrayInputStream(imageData));
                obsClient.putObject(putObjectRequest);
                // 关闭连接，修改图片
                obsClient.close();

            } catch (Exception e) {
                log.info(e.getMessage());
                obsClient.close();
            }
            return imageData;
        } catch (Exception e) {
            log.info(e.getMessage());
            // 返回错误响应
            return null;
        }
    }
}
